<template>
  <div class="watch-wrap">
    <div class="record">{{ record | stopWatch( pause ) }}</div>
    <div>
      <span class="btn" @click="start">{{ pause ? '停止' : '启动' }}</span>
      <span class="btn" @click="reset">{{ pause ? '计次' : '复位' }}</span> 
      <span class="lastRecordToNow">{{ lastRecordToNow | stopWatch( pause ) }}</span>
    </div>
    <div class="record-wrap">
      <div class="record-item" v-for="( item, index ) in recordList" :key="index">
        <span>{{ index }}:</span>
        <span>{{ item | stopWatch( false ) }}</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      timer: null,
      startDate: 0,
      base: 0,
      record: 0,
      lastRecord: 0,
      lastRecordToNow: 0,
      recordList: [],
      pause: false
    }
  },
  filters:{
    stopWatch( val, pause ){
      val = +val 
      if( isNaN( val ) ) val = 0;
      let d = new Date( val );
      let s = d.toGMTString().slice(-12,-4) + '.'
      let e = pause ? '***' : d.getMilliseconds().toString().padStart(3,0)
      return  s + e ;
    }
  },
  methods: {
    start(){
      this.base = this.record
      this.startDate = + new Date()
      if( this.pause ){
        // 暂停
        this.record = new Date() - this.startDate + this.base
        this.lastRecordToNow = this.record - this.lastRecord

        this.base = this.record
        clearInterval( this.timer )
      }else{
        console.log('计时')
        this.timer = setInterval(()=>{
          this.record = new Date() - this.startDate + this.base
          this.lastRecordToNow = this.record - this.lastRecord
        }, 0)
      }
      this.pause = !this.pause
    },
    reset(){
      if( this.pause ){
        // 计次
        console.log('计次')
        this.lastRecord = this.record
        this.recordList.push( this.lastRecordToNow )
      }else{
        // 复位
        this.base = 0;
        this.record = 0
        this.lastRecordToNow = 0
        this.recordList = []
      }
    },
  },
  destroyed(){
    clearInterval( this.timer )
  }
};
</script>
<style lang="scss" scoped>
.watch-wrap{
  box-sizing: border-box;
  width: 100vh;
  height: 100vw;
  transform: rotateZ(90deg) translate(0%,-100%);
  transform-origin: left top;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.record{
  font-size: 112px;
  margin-bottom: 20px;
}
.btn,.lastRecordToNow{
  font-size: 50px;
  padding: 20px;
  display: inline-block;
  margin-right:20px;
  border: 1px #000 dashed;
}
.lastRecordToNow{
  margin: 0;
}
.btn:active{
  background-color: #aaa;
}
.record-wrap{
  padding-top: 20px;
  flex: 1;
  overflow: auto;
}
.record-item{
  display: inline-block;
  margin: 0 15px 10px 0;
  font-size: 26px;
}
</style>